package com.chenwenxuan.sync.ui;

import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.swing.AbstractButton;
import javax.swing.ImageIcon;

import net.sf.image4j.codec.ico.ICODecoder;

public class ImageIconResources {
	
	private Map<String, ImageIcon> iconTable = new HashMap<String, ImageIcon>();

	private static final String PRFFIX = "./images/";
	
	public static final String ICON_TREE_ICON_FOLDER_OPEN = "folder-open-3.ico";
	public static final String ICON_TREE_ICON_FOLDER = "folder.ico";
	public static final String ICON_FROM_ICON_TASKS = "tasks.ico";
	public static final String ICON_FROM_ICON_ADD_TASK = "list-add-4.ico";
	
	
	
	public static final String ICON_FROM_ICON_EDIT = "edit-6.ico";
	public static final String ICON_FROM_ICON_SAVE = "document-save-5.ico";
	public static final String ICON_FROM_ICON_CANCEL = "dialog-cancel-4.ico";
	
	public static final String [] ICON_KEYS = 
			new String[]{
				ICON_TREE_ICON_FOLDER_OPEN, ICON_TREE_ICON_FOLDER, ICON_FROM_ICON_EDIT, ICON_FROM_ICON_SAVE,
				ICON_FROM_ICON_CANCEL, ICON_FROM_ICON_TASKS, ICON_FROM_ICON_ADD_TASK
			};
	
	private static ImageIconResources thisInstance;
	
	public static void setIcon(AbstractButton button, String icon) {
		
		ImageIcon imageIcon = getIconImage(icon);
		
		if (imageIcon ==null ) return;
		
		button.setIcon(imageIcon);
		
		
	}
	
	public static ImageIcon getIconImage(String key) {
		if ( thisInstance == null)
			return null;
		return thisInstance.iconTable.get(key);
	}
	
	public ImageIcon getIcon(String key) {
		if ( thisInstance == null)
			return null;
		return thisInstance.iconTable.get(key);
	}
	
	public void init() {
		thisInstance = this;
	}
	
	public ImageIconResources() {
		
		try {
			ClassLoader loader = ImageIconResources.class.getClassLoader();
			String [] keys = ICON_KEYS;
			for ( int i = 0; i < keys.length; i++ ) {
				String key = keys[i];
				String path = PRFFIX + key;
				try {
					InputStream iconinput = loader.getResourceAsStream(path);
					BufferedImage image = ICODecoder.read(iconinput).get(0);
					iconTable.put(key, new ImageIcon(image));
					iconinput.close();
					System.out.println("Loading ImageIcon Ok. key=" + key + " path=" + path );
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println("Error Loading ImageIcon. key=" + key + " path=" + path );
				}
			}	
		} catch (Throwable t) {
			t.printStackTrace();
		}
		
	}

}
